/******************************************************************************
 *  Copyright 2013 Bernhard Grünewaldt                                        *
 *                                                                            *
 *  Licensed under the Apache License, Version 2.0 (the "License");           *
 *  you may not use this file except in compliance with the License.          *
 *  You may obtain a copy of the License at                                   *
 *                                                                            *
 *      http://www.apache.org/licenses/LICENSE-2.0                            *
 *                                                                            *
 *  Unless required by applicable law or agreed to in writing, software       *
 *  distributed under the License is distributed on an "AS IS" BASIS,         *
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *
 *  See the License for the specific language governing permissions and       *
 *  limitations under the License.                                            *
 ******************************************************************************/
package com.google.code.greenwood.confluencemavenreleaseinfomacro.parser;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;

import com.google.code.greenwood.confluencemavenreleaseinfomacro.pojo.ModuleReleaseVersion;
import com.google.code.greenwood.confluencemavenreleaseinfomacro.pojo.ReleaseInformation;

public class HttpReleaseInfoDownloader {

	public File downloadMavenReleaseRecursively(URL urlToPomXml, String username, String password) throws Exception {
		
		ReleaseInformation rinfo = new ReleaseInformation();
		
		String tempdir = System.getProperty("java.io.tmpdir");
		if (!tempdir.endsWith(System.getProperty("file.separator"))) { tempdir += System.getProperty("file.separator"); }
		String parantpomFilenameDir = tempdir + "mavenrelinfo"+getClass().toString() + System.getProperty("file.separator");
		File parantpomFilenameDirf = new File(parantpomFilenameDir);
		parantpomFilenameDirf.mkdirs();
     	File parentpom = downloadFile(urlToPomXml, new File(parantpomFilenameDir+"pom.xml"), username, password);

    	
        DomDocumentToReleaseInfoParser parser = new DomDocumentToReleaseInfoParser();
        rinfo = parser.parsePomFilesRecursive(parentpom, false);
        
        
        for (ModuleReleaseVersion module : rinfo.getModules()) {
        	String modulefile = parantpomFilenameDir + module.getName()+System.getProperty("file.separator");
        	String moduleurl = urlToPomXml.toExternalForm().replace("pom.xml", module.getName()+"/pom.xml");       	
        	File dir = new File(modulefile);
        	if (!dir.isDirectory()) { dir.mkdir(); }
        	downloadFile(new URL(moduleurl), new File(modulefile+"pom.xml"), username, password);
        }
        
        
        return parentpom;
	}

	public File downloadFile(URL url, File downloadDestination, String username, String password) throws Exception {
		HttpClient client = new HttpClient();
		if (username != null) {
	        Credentials cred = new UsernamePasswordCredentials(username,password);
	        client.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),cred);
		}
		String urls = url.toExternalForm();
        GetMethod get = new GetMethod(urls);
        client.executeMethod(get);      
        if (get.getStatusCode() == 401) {
        	throw new HttpException("HTTP statuscode 401 - unauthorized");
        }
        if (get.getStatusCode() == 404) {
        	throw new HttpException("HTTP statuscode 404 - not found");
        }
        if (get.getStatusCode() != 200) {
        	throw new HttpException("HTTP statuscode "+get.getStatusCode());
        }

        InputStream inputstream = get.getResponseBodyAsStream();
        
        File downloadedpomfilename = downloadDestination;
        downloadedpomfilename.createNewFile();
        
    	OutputStream out = new FileOutputStream(downloadedpomfilename);
    	 
    	int read = 0;
    	byte[] bytes = new byte[1024];
     
    	while ((read = inputstream.read(bytes)) != -1) {
    		out.write(bytes, 0, read);
    	}
     
    	inputstream.close();
    	out.flush();
    	out.close();
    	
    	return downloadDestination;
	}
}
